import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import {asyncGet} from "@/plugins/axios"

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        component: () => import('@/views/index'),
        children: [
            {
                path: '/question/common',
                name: 'common',
                component: () => import('@/views/main/questionBank/question/question')
            },
            {
                path: '/question/private',
                name: 'private',
                component: () => import('@/views/main/questionBank/question/question')
            },
            {
                path: '/question/questionReview',
                name: 'questionReview',
                component: () => import('@/views/main/questionBank/question/questionReview')
            },
            {
                path: '/answer/paper',
                name: 'paper',
                component: () => import('@/views/main/answer/paper')
            },
            {
                path: '/user/detail',
                name: 'detail',
                component: () => import('@/views/main/user/detail')
            }
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/main/user/login')
    },
    {
        path: '/registered',
        name: 'registered',
        component: () => import('@/views/main/user/registered')
    },
    {
        path: '/tempAccount',
        name: 'tempAccount',
        component: () => import('@/views/main/user/tempAccount')
    },
    {
        path: '/changePassword',
        name: 'changePassword',
        component: () => import('@/views/main/user/changePassword')
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// 过滤器白名单
const whiteList = ['/login', '/registered', '/tempAccount']
// 是否有菜单数据
let hasMenus = false
// 前端过滤器
router.beforeEach(async (to, from, next) => {
    const token = store.getters.GET_TOKEN
    // 纯净路径（白名单中包含的路径）
    const whitePath = whiteList.indexOf(to.path) !== -1
    if (token || whitePath) {
        if (whitePath || (hasMenus && !Vue.reloadMenu)) {
            next()
        } else {
            // 加载菜单
            // 向后端发送请求请求菜单数据
            const roleId = store.getters.GET_ROLE
            const data = JSON.parse(JSON.stringify(store.getters.GET_ROUTES))
            const currentRouter = router.options.routes;
            if (data === null || data.length === 0) {
                const routesBehind = await asyncGet('/menu/componentRouter', {})
                const handleRoute = JSON.parse(JSON.stringify(routesBehind.data.data))
                // 加工后端返回的routesBehind路由
                handleRoute.forEach(item => {
                    if (item.roleIds.indexOf(roleId) !== -1) {
                        item.component = loadView(item.component)
                        currentRouter[0].children.push(item)
                    }
                })
                store.commit('SET_ROUTES', routesBehind.data.data)
            } else {
                // 加工后端返回的routes路由
                data.forEach(item => {
                    if (item.roleIds.indexOf(roleId) !== -1) {
                        item.component = loadView(item.component)
                        currentRouter[0].children.push(item)
                    }
                })
            }

            router.matcher = new VueRouter({
                mode: 'history',
                base: process.env.BASE_URL
            }).matcher
            // TODO 第一次登录执行此代码之后 报异常 Error: Redirected when going from "/login" to "/home" via a navigation guard.
            router.addRoutes(currentRouter)

            hasMenus = true
            Vue.reloadMenu = false
            // TODO next(to)导致路由重复跳转了一次  如何改成next()直接放行请求
            next(to)
        }
    } else {
        next('/login')
    }
})

const loadView = (view) => { // 路由懒加载
    return (resolve) => require([`@/views/${view}`], resolve)
}


export default router
